<?php

namespace Biz\service\theParagraph;

use Biz\model\GoodsBasicInfo;
use Biz\model\ShopFavorite;
use Biz\model\theParagraph\Collocation as mCollocation;
use Biz\model\theParagraph\CollocationGoods as mCollocationGoods;
use Biz\model\theParagraph\CollocationImg as mCollocationImg;
use Biz\model\theParagraph\Room as mRoom;
use Biz\model\theParagraph\Store as mStore;
use Biz\service\activity\Page;
use Biz\service\Sku;
use Doraemon\tools\HhzClient;
use Doraemon\tools\ImgUrl;
/**
 * @deprecated
 */
class Store
{
    const COLLOCATION_IMG_DELETE_KEY_PREFIX = 'I_';
    const COLLOCATION_GOODS_DELETE_KEY_PREFIX = 'G_';

    public static function getCollocationsByCollocationIds($collocationIds)
    {
        $collocationInfos = mCollocation::getCollocationByIds($collocationIds);
        $roomIds = array_column($collocationInfos, 'room_id');
        $roomInfos = mRoom::getRoomsByIds($roomIds);
        $formatRooms = [];
        foreach ($roomInfos as $roomInfo) {
            $formatRooms[$roomInfo['id']] = $roomInfo;
        }
        $storeIds = array_unique(array_column($collocationInfos, 'store_id'));
        $storeInfos = mStore::getStoresByIds($storeIds);
        $formatStore = [];
        foreach ($storeInfos as $storeInfo) {
            $formatStore[$storeInfo['id']] = [
                'id' => $storeInfo['id'],
                'title' => $storeInfo['title'],
                'location' => $storeInfo['location'],
                'position' => $storeInfo['position']
            ];
        }

        $formatCollocationInfos = [];
        foreach ($collocationInfos as $collocationInfo) {
            $goods = mCollocationGoods::getGoodsByCollocationId($collocationInfo['id']);
            $goods = array_filter($goods, function($v){
                return $v['goods_info']['status'] == GoodsBasicInfo::STATUS_APP_NOMAL;
            });
            $goods = array_values($goods);
            $formatCollocationInfos[$collocationInfo['id']] = [
                'id' => $collocationInfo['id'],
                'store_info' => $formatStore[$collocationInfo['store_id']],
                'room_title' => $formatRooms[$collocationInfo['room_id']]['title'],
                'title' => $collocationInfo['title'],
                'sub_title' => $collocationInfo['sub_title'],
                'type' => mRoom::ROOM_TYPE_DEFAULE,
                'style' => $collocationInfo['style'],
                'sub_script' => $collocationInfo['sub_script'],
                'cover_img' => $collocationInfo['cover_img'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $collocationInfo['cover_img'], ImgUrl::IMAGE_SIZE_OP_ORI) : '',
                'banner_img' => $collocationInfo['banner_img'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $collocationInfo['banner_img'], ImgUrl::IMAGE_SIZE_OP_ORI) : '',
                'total_goods' => count($goods),
                'goods' => array_slice($goods, 0, 4)
            ];
        }
        return $formatCollocationInfos;
    }

    public static function isFavorite(array $collocationIds, $uid)
    {
        return ShopFavorite::is_favorited($uid, $collocationIds, ShopFavorite::TYPE_ROOM, HhzClient::APPTYPE_PARAGRAPH_MINIPROGRAM);
    }

    public static function getCollocationsByGoodsIds($goodsId)
    {
        $collocationIds = mCollocationGoods::getCollocationIdsByGoodsId($goodsId);
        if ($collocationIds) {
            return array_values(self::getCollocationsByCollocationIds($collocationIds));
        } else {
            return [];
        }
    }

    public static function collocationsFavList($uid, $page, $appSource)
    {
        $favList = ShopFavorite::getFavInfos($uid, ShopFavorite::TYPE_ROOM, $appSource, $page);
        $favList['list'] = self::getCollocationsByCollocationIds(array_column($favList['list'], 'obj_id'));
        $favList['list'] = array_values($favList['list']);
        return $favList;
    }


    public static function admGetStoreList($status)
    {
        $storeList = mStore::getStoreList($status);
        return [
            'list' => $storeList,
            'total' => count($storeList)
        ];
    }

    public static function admGetStoreInfo($storeId)
    {
        return mStore::getStoreById($storeId);
    }

    public static function getStoreByAbbr($abbr){
        return mStore::getStoreByAbbr($abbr);
    }

    public static function admGetRoomsList($storeId, $sort = mRoom::SORT_HOMEPAGE, $type = [
        mRoom::ROOM_TYPE_DEFAULE,
        mRoom::ROOM_TYPE_PAGE
    ])
    {
        $rooms = mRoom::getRoomListByStoreId($storeId, [
            mRoom::STATUS_NORMAL,
            mRoom::STATUS_HIDDEN
        ], $sort, $type);
        $roomIds = [];
        $pageIds = [];
        foreach ($rooms as $room) {
            if ($room['type'] == mRoom::ROOM_TYPE_DEFAULE) {
                $roomIds[] = $room['id'];
            } elseif ($room['type'] == mRoom::ROOM_TYPE_PAGE) {
                $pageIds[] = $room['page_id'];
            }
        }
        $collocationInfos = mCollocation::getValidCollocationByRoomIds($roomIds);
        $pageInfos = Page::getPageGoods($pageIds);
        foreach ($rooms as &$room) {
            $room['collocation_title'] = '';
            if ($room['type'] == mRoom::ROOM_TYPE_DEFAULE) {
                foreach ($collocationInfos as $collocationInfo) {
                    if ($collocationInfo['room_id'] == $room['id']) {
                        $room['content'] = $collocationInfo['title'];
                        break;
                    }
                }
            } elseif ($room['type'] == mRoom::ROOM_TYPE_PAGE) {
                foreach ($pageInfos as $pageInfo) {
                    if ($pageInfo['id'] == $room['page_id']) {
                        $room['content'] = $pageInfo['title'];
                        break;
                    }
                }
            }

        }
        return [
            'list' => $rooms,
            'total' => count($rooms)
        ];
    }

    public static function admGetRoomInfo($roomId)
    {
        return mRoom::getRoomById($roomId);
    }

    public static function admGetCollocationList($storeId)
    {
        return mCollocation::getCollocationListByRoomId($storeId, [
            mCollocation::STATUS_NORMAL,
            mCollocation::STATUS_HIDDEN
        ]);
    }

    public static function admGetCollocationInfo($collocationId)
    {
        $collocationInfo = mCollocation::getCollocationById($collocationId);
        $collocationInfo['cover_img_url'] = $collocationInfo['cover_img'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $collocationInfo['cover_img'], ImgUrl::IMAGE_SIZE_OP_ORI) : '';
        $collocationInfo['banner_img_url'] = $collocationInfo['banner_img'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $collocationInfo['banner_img'], ImgUrl::IMAGE_SIZE_OP_ORI) : '';
        return $collocationInfo;
    }

    public static function admGetImgsByCollocationId($collocationId)
    {
        $imgs = mCollocationImg::getImgByCollocationId($collocationId);
        foreach ($imgs as &$img) {
            $img['img_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $img['pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI);
            $img['delete_key'] = self::COLLOCATION_IMG_DELETE_KEY_PREFIX . $img['id'];
        }
        return [
            'list' => $imgs,
            'total' => count($imgs)
        ];
    }

    public static function admGetGoodssByCollocationId($collocationId)
    {
        $goodsList = mCollocationGoods::getGoodsByCollocationId($collocationId);
        foreach ($goodsList as &$goods) {
            $goods['delete_key'] = self::COLLOCATION_GOODS_DELETE_KEY_PREFIX . $goods['id'];
            if(isset($goods['goods_info'])) {
                $skuInfo = Sku::Sku($goods['goods_info']['id'], Sku::FIELDS_GROUP_ALL);
                $skuList = [];
                foreach ($skuInfo['sku_info'] as $sku) {
                    $skuList[$sku['sku_id']] = $sku['sku_desc'];
                }
                $goods['sku_list'] = $skuList;
            }

        }
        return [
            'list' => $goodsList,
            'total' => count($goodsList)
        ];
    }

    public static function getStoreIndex($storeId)
    {
        $storeInfo = mStore::getStoreById($storeId);
        if ($storeInfo['status'] != mStore::STATUS_NORMAL) {
            throw new \Exception('店铺不存在');
        }
        $rooms = mRoom::getRoomListByStoreId($storeId, mRoom::STATUS_NORMAL, mRoom::SORT_INDEX, mRoom::ROOM_TYPE_DEFAULE);
        $roomIds = array_column($rooms, 'id');
        $collocationInfos = mCollocation::getValidCollocationByRoomIds($roomIds);
        $formatRoomList = [];
        foreach ($rooms as $room) {
            foreach ($collocationInfos as $collocationInfo) {
                $goods = mCollocationGoods::getGoodsByCollocationId($collocationInfo['id'], false);
                if ($collocationInfo['room_id'] == $room['id']) {
                    $formatRoomList[] = [
                        'id' => $collocationInfo['id'],
                        'room_title' => $room['title'],
                        'title' => $collocationInfo['title'],
                        'sub_title' => $collocationInfo['sub_title'],
                        'sub_script' => $collocationInfo['sub_script'],
                        'cover_img' => $collocationInfo['cover_img'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $collocationInfo['cover_img'], ImgUrl::IMAGE_SIZE_OP_ORI) : '',
                        'total_goods' => count($goods)
                    ];
                    break;
                }
            }
        }
        return $formatRoomList;
    }

    public static function getValidCollocationIdByRoomId($roomId)
    {
        return mCollocation::getValidCollocationIdByRoomId($roomId);
    }

    public static function getStoreInfo($storeId)
    {
        $storeInfo = mStore::getStoreById($storeId);
        if ($storeInfo['status'] != mStore::STATUS_NORMAL) {
            throw new \Exception('店铺不存在');
        }
        $rooms = mRoom::getRoomListByStoreId($storeId);
        $roomIds = [];
        $pageIds = [];
        foreach ($rooms as $room) {
            if ($room['type'] == mRoom::ROOM_TYPE_DEFAULE) {
                $roomIds[] = $room['id'];
            } elseif ($room['type'] == mRoom::ROOM_TYPE_PAGE) {
                $pageIds[] = $room['page_id'];
            }
        }
        $collocationInfos = mCollocation::getValidCollocationByRoomIds($roomIds);
        $pageInfos = Page::getPageGoods($pageIds);
        $formatRoomList = [];
        $formatRoomIndex = [];
        $indexSort = [];
        foreach ($rooms as $room) {
            if ($room['type'] == mRoom::ROOM_TYPE_DEFAULE) {
                foreach ($collocationInfos as $collocationInfo) {
                    if ($collocationInfo['room_id'] == $room['id']) {
                        $collocationGoods = mCollocationGoods::getGoodsByCollocationId($collocationInfo['id']);
                        $collocationGoods = array_values(array_filter($collocationGoods, function ($goods) {
                            return $goods['goods_info']['status'] == GoodsBasicInfo::STATUS_APP_NOMAL;
                        }));
                        $totalGoodsNum = count($collocationGoods);
                        $collocationGoods = array_slice($collocationGoods, 0, 4);
                        $subScript = mCollocation::SUB_SCRIPT_NONE;
                        if ($collocationInfo['sub_script'] != mCollocation::SUB_SCRIPT_NONE) {
                            $date = date('Y-m-d H:i:s');
                            if (($collocationInfo['sub_script_start_time'] == mCollocation::DEFAULE_DATETIME || $collocationInfo['sub_script_start_time'] < $date) && ($collocationInfo['sub_script_end_time'] == mCollocation::DEFAULE_DATETIME || $collocationInfo['sub_script_end_time'] > $date)) {
                                $subScript = $collocationInfo['sub_script'];
                            }
                        }
                        $formatRoomList[] = [
                            'id' => $collocationInfo['id'],
                            'room_title' => $room['title'],
                            'title' => $collocationInfo['title'],
                            'sub_title' => $collocationInfo['sub_title'],
                            'type' => mRoom::ROOM_TYPE_DEFAULE,
                            'style' => $collocationInfo['style'],
                            'sub_script' => $subScript,
                            'cover_img' => $collocationInfo['cover_img'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $collocationInfo['cover_img'], ImgUrl::IMAGE_SIZE_OP_ORI) : '',
                            'total_goods' => $totalGoodsNum,
                            'goods' => array_column($collocationGoods, 'goods_info')
                        ];
                        $indexSort[] = $room['index_sort'];
                        $formatRoomIndex[] = [
                            'id' => $collocationInfo['id'],
                            'room_title' => $room['title'],
                            'title' => $collocationInfo['title'],
                            'sub_title' => $collocationInfo['sub_title'],
                            'sub_script' => $subScript,
                            'cover_img' => $collocationInfo['cover_img'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $collocationInfo['cover_img'], ImgUrl::IMAGE_SIZE_OP_ORI) : '',
                            'total_goods' => $totalGoodsNum
                        ];
                        break;
                    }
                }
            } elseif ($room['type'] == mRoom::ROOM_TYPE_PAGE) {
                foreach ($pageInfos as $pageInfo) {
                    if ($room['page_id'] == $pageInfo['id']) {
                        $pageInfo['type'] = mRoom::ROOM_TYPE_PAGE;
                        $formatRoomList[] = $pageInfo;
                        break;
                    }
                }
            }
        }
        array_multisort($indexSort, $formatRoomIndex);
        $formatStoreInfo = [
            'id' => $storeInfo['id'],
            'title' => $storeInfo['title'],
            'list' => $formatRoomList,
            'index' => $formatRoomIndex
        ];
        return $formatStoreInfo;
    }

    public static function GetCollocationInfo($collocationId, $uid = 0)
    {
        $collocationInfo = mCollocation::getCollocationById($collocationId);
        if ($collocationInfo['status'] != mCollocation::STATUS_NORMAL) {
            throw new \Exception('空间不存在');
        }
        $roomInfo = mRoom::getRoomById($collocationInfo['room_id']);
        if ($roomInfo['status'] != mRoom::STATUS_NORMAL) {
            throw new \Exception('空间不存在');
        }
        $imgs = mCollocationImg::getImgByCollocationId($collocationInfo['id']);
        $goods = mCollocationGoods::getGoodsByCollocationId($collocationInfo['id']);
        return self::_formatCollocationInfo($roomInfo, $collocationInfo, $imgs, $goods, $uid);
    }

    private static function _formatCollocationInfo($roomInfo, $collocationInfo, $imgs, $goodsList, $uid = 0)
    {
        if ($uid) {
            $isFav = self::isFavorite([$collocationInfo['id']], $uid);
        } else {
            $isFav = [];
        }
        $formatGoods = [];
        foreach ($goodsList as $goods) {
            if ($goods['goods_info']['status'] == GoodsBasicInfo::STATUS_APP_NOMAL) {
                $skuList = Sku::Sku($goods['goods_id'], Sku::FIELDS_GROUP_SKU_INFO);
                $goods['goods_info']['sku_id'] = $skuList[0]['sku_id'];
                foreach ($skuList as $sku) {
                    if ($sku['sku_id'] == $goods['sku_id']) {
                        $goods['goods_info']['sku_id'] = $goods['sku_id'];
                        break;
                    }
                }
                $formatGoods[] = $goods['goods_info'];
            }
        }
        $storeInfo = mStore::getStoreById($collocationInfo['store_id']);
        $formatData = [
            'id' => $collocationInfo['id'],
            'store_id' => $collocationInfo['store_id'],
            'store_info' => [
                'id' => $storeInfo['id'],
                'title' => $storeInfo['title'],
                'location' => $storeInfo['location'],
            ],
            'room_title' => $roomInfo['title'],
            'title' => $collocationInfo['title'],
            'sub_title' => $collocationInfo['sub_title'],
            'inspiration' => $collocationInfo['inspiration'],
            'cover_img' => ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $collocationInfo['cover_img'], ImgUrl::IMAGE_SIZE_OP_ORI),
            'is_fav' => (isset($isFav[$collocationInfo['id']]) && $isFav[$collocationInfo['id']]) ? 1 : 0,
            'imgs' => array_map(function ($img) {
                return ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $img['pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI);
            }, $imgs),
            'goods' => $formatGoods
        ];
        return $formatData;
    }

    public static function getStoreList($format = true)
    {
        $storeList = mStore::getStoreList(mStore::STATUS_NORMAL);
        return $format ? self::_formatStoreList($storeList) : $storeList;
    }

    private static function _formatStoreList($storeList)
    {
        $formatData = [];
        foreach ($storeList as $store) {
            $formatData[] = [
                'id' => $store['id'],
                'title' => $store['title']
            ];
        }
        return $formatData;
    }

    /**
     * @desc 节选自提店铺列表
     * @return array
     */
    public static function getSelfMentionList()
    {
        $formatData = [];
        $storeList = self::getStoreList(false);
        if ($storeList) {
            foreach ($storeList as $store) {
                $formatData[] = [
                    'id' => $store['id'],
                    'title' => $store['title'],
                    'location' => $store['location'],
                    'position' => $store['position'],
                ];
            }
        }
        return $formatData;
    }

}
